<template>
  <BasicTable @register="registerTable" :showIndexColumn="false"> </BasicTable>
</template>
<script lang="ts" setup>
  import { BasicTable, useTable } from '@/components/Table'
  import { watch, onMounted } from 'vue'
  import dayjs, { Dayjs } from 'dayjs'

  const props = defineProps({
    loading: { type: Boolean },
  })

  const [registerTable, { setColumns, setTableData, setLoading }] = useTable({
    columns: [],
    canResize: false,
    scroll: { y: '100%' },
    pagination: false,
  })

  onMounted(() => {
    setLoading(true)
  })

  watch(
    () => props.loading,
    (val) => {
      setLoading(val)
    },
  )

  const formatHeader = (headerData) => {
    const headerList: any = [
      {
        // title: '总计',
        dataIndex: 'name',
        width: 120,
        fixed: 'left',
        merge: true,
        customRender: ({ text }) => {
          return text || '--'
        },
      },
      {
        title: '总计',
        dataIndex: 'total',
        width: 120,
        fixed: 'left',
        merge: true,
        customRender: ({ text }) => {
          return text || '--'
        },
      },
    ]

    if (headerData && headerData.length > 0) {
      headerData.forEach((item) => {
        headerList.push({
          title: `${dayjs(item).format('D')}`,
          dataIndex: `${dayjs(item).format('D')}`,
          width: 100,
          customRender: ({ text }) => {
            return text || '--'
          },
        })
      })
    }
    setColumns(headerList)
  }

  const formatTableData = (tableData) => {
    if (tableData && tableData.length > 0) {
      const data: any[] = []
      tableData.forEach((item, index) => {
        let obj: any = {
          name: item.name,
          // total: item.total
        }

        if (item.data.length > 0) {
          item.data.forEach((e, o) => {
            obj[o] = e
          })
        }
        data.push(obj)
      })
      setTableData(data)
    }
  }

  const setData = (header, tableData) => {
    console.log('header---------', header)
    console.log('tableData---------', tableData)
    formatHeader(header)
    formatTableData(tableData)
  }
  defineExpose({
    setData,
  })
</script>
